<?php

namespace App\Service\WorkOrder\Message;

use App\Enums\WorkOrder\OrderEnum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\CommonService;
use App\Service\Common\SmsService;
use App\Service\OpenShop\Feishu\MessageSendService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\WorkOrder\Manager\ManagerService;
use App\Support\FeishuMsgSupport;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;


/**
 *
 * @property $shopCode 门店编号 e.g. 1122
 * @property $shopName 门店名称 e.g. 上海数字研发
 * @property $workOrderNo e.g. AA00202206241204540034
 * @property $workChildName 工单二级类型名字 e.g. 美团外卖
 * @property $workShopUserName 工单加盟商姓名 e.g. 张三
 * @property $workShopUserMobile 工单加盟商手机号 e.g. 1311111111
 * @property $createdAt 创建时间 e.g. 2022年09月02日12:14:00
 * @property $updatedAt 更新时间 e.g. 2022年09月02日12:13:57
 * @property $getJumpUrl 跳转地址
 *
 */
class SendFsService extends BaseMessageService
{
    /**
     * 工单申请结果飞书
     * @param bool $result true完成 false关闭
     * @return void
     */
    public function workOrderApplyResult(bool $result): void
    {
        $problemPidText     = $this->workOrderApplyMainModel->problemPidText;
        $problemChildIdText = $this->workOrderApplyMainModel->problemChildText;
        $role               = OrderEnum::PROBLEM_PID_TO_ROLE[$this->workOrderApplyMainModel->problemPid] ?? 0;

        // 发送给客服
        $fs = (new MessageSendService())->setModule(UserPermissionAuth::MODULE_WORK_ORDER);

        if ($result) {
            $fs = $fs->setText('**【工单完成】工单处理结果**');
        } else {
            $fs = $fs->setText('**【工单关闭】工单处理结果**');
        }

        $operateNames = WorkOrderApplyManagerModel::query()
                                                  ->where('workOrderNo', $this->workOrderApplyMainModel->workOrderNo)
                                                  ->where('role', $role)
                                                  ->pluck('managerName')
                                                  ->implode(',', '');

        $fs->setField('工单类型', "{$problemPidText} {$problemChildIdText}")
           ->setField('工单号', $this->workOrderApplyMainModel->workOrderNo)
           ->setField('操作人', $operateNames)
           ->setReceiveFeiShuIds($this->getFsIds(WorkOrderUserRoleModel::ROLE_TYPE_1))
           ->setUrl($this->getUrl())
           ->send();
    }

    /**
     * 负责人关闭工单
     * @param $managerId
     * @return void
     */
    public function personCloseWorkOrder($managerId): void
    {
        $problemPidText     = $this->workOrderApplyMainModel->problemPidText;
        $problemChildIdText = $this->workOrderApplyMainModel->problemChildText;

        // 发送给客服
        $fs = (new MessageSendService())->setModule(UserPermissionAuth::MODULE_WORK_ORDER);

        $fs = $fs->setText('**【工单关闭】负责人关闭工单**');


        $operateName = (string)WorkOrderApplyManagerModel::query()
                                                         ->where('workOrderNo',
                                                             $this->workOrderApplyMainModel->workOrderNo)
                                                         ->where('managerId', $managerId)
                                                         ->value('managerName');

        $fs->setField('工单类型', "{$problemPidText} {$problemChildIdText}")
           ->setField('工单号', $this->workOrderApplyMainModel->workOrderNo)
           ->setField('操作人', $operateName)
           ->setReceiveFeiShuIds($this->getFsIds(WorkOrderUserRoleModel::ROLE_TYPE_1))
           ->setUrl($this->getUrl())
           ->send();
    }

    /**
     * 处理人收到客服分配的工单后，收到飞书推送 - 优化版本通知
     * @param int $role
     * @return void
     */
    public function kfDistributeProcessorOptimize(int $role, array $sendFsIds = [], array $userIds = [])
    {
        $template        = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/waimaiOpenNotify.json');
        $waimaiAllPeople = ManagerService::getWaiMaiPeople($this->getShopProvinceCode());

        $templateJson = json_decode(vsprintf($template,
            [
                '待确认',
                "外卖（{$waimaiAllPeople['waimai']}）+私域（{$waimaiAllPeople['siyu']}）"

            ]),
            true);

        $userList = $this->getFsIds($role, $userIds);

        $fsUserList = array_merge($sendFsIds, $userList);

        $result = MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_WORK_ORDER,
            $fsUserList);

//        return $result;
    }

    /**
     * 外卖消息推送
     * @param int $role
     * @return void
     */
    public function kfWaimaiOpenFinalMessage()
    {
        $template = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');

        $templateJson = json_decode(vsprintf($template,
            [
                '建店申请通过，已提交外卖平台处理',
                '已完成',
                '查看详情'
            ]),
            true);

        $departmentId = 'od-5937a115f5e23b277dcef6eac5b018aa'; // 数字研发
        // 异常订单
        if (config('app.env') == 'prod') {
            $departmentId = 'od-22740c11973fd021a6aa53f32d17b72d'; // 外卖运营
        }
        $result = MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_WORK_ORDER, [], [
            $departmentId
        ]);
    }

    /**
     * 外卖消息省总推送
     * @param int $role
     * @return void
     */
    public function kfWaimaiOpenFinalPraesesMessage()
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');
        $templateJson = json_decode(vsprintf($template,
            [
                '建店申请通过，已提交外卖平台处理',
                '已完成',
                '查看详情'
            ]),
            true);

        $shopInfo         = $this->getShopInfo();
        $organizationUser = OrganizationManageService::getProvinceInfoByProvinceCode($shopInfo->province);

        $organizationUser['operationUserFeishuId'] = '';
        if (!empty($organizationUser) && !empty($organizationUser['operationUid'])) {
            $operationUser = RmsUserService::getRmsUserInfoByUserIds($organizationUser['operationUid']);
            if ($operationUser['code'] == 200) {
                $organizationUser['operationUserFeishuId'] = $operationUser['data'][0]['feishuUserId'];
            }
        }
        MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_WORK_ORDER,
            [
                $organizationUser['operationUserFeishuId']
            ]);
    }


    /**
     * 外卖省总推送消息
     * @param int $role
     * @return void
     */
    public function kfDistributeWaimaiProvince()
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');
        $templateJson = json_decode(vsprintf($template,
            [
                '提交开通申请',
                '待审核',
                '查看详情'
            ]),
            true);

        $shopInfo         = $this->getShopInfo();
        $organizationUser = OrganizationManageService::getProvinceInfoByProvinceCode($shopInfo->province);

        $organizationUser['operationUserFeishuId'] = '';
        if (!empty($organizationUser) && !empty($organizationUser['operationUid'])) {
            $operationUser = RmsUserService::getRmsUserInfoByUserIds($organizationUser['operationUid']);
            if ($operationUser['code'] == 200) {
                $organizationUser['operationUserFeishuId'] = $operationUser['data'][0]['feishuUserId'];
            }
        }
        MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_WORK_ORDER,
            [
                $organizationUser['operationUserFeishuId']
            ]);
    }

    /**
     * 外卖全员发消息
     *
     * @throws GuzzleException
     */
    public function kfDistributeWaimaiGroup()
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');
        $templateJson = json_decode(vsprintf($template,
            [
                '提交开通申请',
                '待审核',
                '查看详情'
            ]),
            true);

        $departmentId = 'od-5937a115f5e23b277dcef6eac5b018aa'; // 数字研发
        // 异常订单
        if (config('app.env') == 'prod') {
            $departmentId = 'od-22740c11973fd021a6aa53f32d17b72d'; // 外卖运营
        }
        $result = MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_WORK_ORDER, [], [
            $departmentId
        ]);
    }

    /**
     * 外卖消息推送
     * @param int $role
     * @return void
     */
    public function kfDistributeWaimaiManage(int $role, array $userIds = [])
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');
        $templateJson = json_decode(vsprintf($template,
            [
                '工单需要处理！',
                '运营伙伴已入企微群',
                '立即处理'
            ]),
            true);
        $userList     = $this->getFsIds($role, $userIds);
        foreach ($userList as $fsId) {
            MessageSendService::sendMessage($fsId, 'user_id', $templateJson, 'interactive',
                UserPermissionAuth::MODULE_WORK_ORDER);
        }
    }

    /**
     * 外卖功能开通 通知
     */
    public function kfWaimaiFunctionOpenMessage(int $role, array $userIds = [], string $status = '待审核')
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');
        $templateJson = json_decode(vsprintf($template,
            [
                '提交开通申请',
                $status,
                '立即处理'
            ]),
            true);

        $userList = $this->getFsIds($role, $userIds);
        foreach ($userList as $fsId) {
            MessageSendService::sendMessage($fsId, 'user_id', $templateJson, 'interactive',
                UserPermissionAuth::MODULE_WORK_ORDER);
        }
    }

    /**
     * 外卖消息推送
     * @param int $role
     * @return void
     */
    public function kfDistributeWaimaiManageGroup(int $sendFsRobotId = 9)
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderCommonNotify.json');
        $templateJson = json_decode(vsprintf($template,
            [
                '提交开通申请',
                '待审核',
                '立即处理'
            ]),
            true);

        BuildFs::newRobot($sendFsRobotId, BuildFs::MSG_TYPE_CARD)->setCardContent($templateJson)->send();
    }


    /**
     * 处理人收到客服分配的工单后，收到飞书推送
     * @param int $role
     * @return void
     */
    public function kfDistributeProcessor(int $role, array $userIds = []): void
    {
        (new MessageSendService())
            ->setModule(UserPermissionAuth::MODULE_WORK_ORDER)
            ->setText('**您有待处理的工单，请及时处理**')
            ->setField('工单号', $this->workOrderApplyMainModel->workOrderNo)
            ->setField('工单类型', $this->workOrderApplyMainModel->getProblemPidTextAttribute())
            ->setField('问题类型', $this->workOrderApplyMainModel->getProblemChildIdTextAttribute())
            ->setReceiveFeiShuIds($this->getFsIds($role, $userIds))
            ->setUrl($this->getUrl())
            ->send();
    }

    /**
     * 工单转交发送飞书消息
     * @param array $feishuIds
     * @return void
     */
    public function transferWorkOrder(array $feishuIds): void
    {
        (new MessageSendService())
            ->setModule(UserPermissionAuth::MODULE_WORK_ORDER)
            ->setText('**您收到一个转交给您的工单，请及时处理**')
            ->setField('工单号', $this->workOrderApplyMainModel->workOrderNo)
            ->setField('工单类型', $this->workOrderApplyMainModel->getProblemPidTextAttribute())
            ->setField('问题类型', $this->workOrderApplyMainModel->getProblemChildIdTextAttribute())
            ->setReceiveFeiShuIds($feishuIds)
            ->setUrl($this->getUrl())
            ->send();
    }

    /**
     * 催办
     * @param array $userIds
     * @param string $operateUsername
     * @return void
     * @throws GuzzleException
     */
    public function cuiBan(array $userIds, string $operateUsername = "商家")
    {
        FeishuMsgSupport::getInstance("您正在处理的工单被{$operateUsername}催办了，请及时处理!", $userIds)
                        ->setModule(UserPermissionAuth::MODULE_WORK_ORDER)
                        ->setContent(
                            [
                                "name"  => "工单类型",
                                "value" => $this->workOrderApplyMainModel->getProblemPidTextAttribute()
                            ],
                            [
                                "name"  => "问题类型",
                                "value" => $this->workOrderApplyMainModel->getProblemChildIdTextAttribute()
                            ],
                            [
                                "name"  => "工单号",
                                "value" => $this->workOrderApplyMainModel->workOrderNo
                            ],
                        )
                        ->workOrderMsgSend([
                            "path" => "workOrder/manage/info/{$this->workOrderApplyMainModel->workOrderNo}?isMainModule=1",
                            "mode" => "window"
                        ], "查看详情");
    }

    /**
     * 给负责人推送，可抢单消息
     * @param array $userIds
     * @return void
     */
    public function enableGrab(array $feishuIds)
    {
        $problemPidText     = $this->workOrderApplyMainModel->problemPidText;
        $problemChildIdText = $this->workOrderApplyMainModel->problemChildIdText;

        (new MessageSendService())
            ->setModule(UserPermissionAuth::MODULE_WORK_ORDER)
            ->setText("**【工单抢单】{$problemPidText} {$problemChildIdText}**")
            ->setField('任务', '您有待处理的工单，请及时处理')
            ->setField('工单号', $this->workOrderApplyMainModel->workOrderNo)
            ->setField('工单类型', $this->workOrderApplyMainModel->getProblemPidTextAttribute())
            ->setField('问题类型', $this->workOrderApplyMainModel->getProblemChildIdTextAttribute())
            ->setReceiveFeiShuIds($feishuIds)
            ->setUrl($this->getUrl())
            ->send();
    }

    private function getUrl()
    {
        $path  = "workOrder/manage/info/{$this->workOrderApplyMainModel->workOrderNo}?isMainModule=1";
        $appid = config("feishu." . UserPermissionAuth::MODULE_WORK_ORDER . ".appID");

        return "https://applink.feishu.cn/client/web_app/open?appId={$appid}&path=$path";
    }

    public function getFsIds(int $role, array $userIds = []): array
    {
        if (!$userIds) {

            $userIds = WorkOrderApplyManagerModel::query()
                                                 ->where('workOrderNo', $this->workOrderApplyMainModel->workOrderNo)
                                                 ->where('role', $role)
                                                 ->pluck('managerId')
                                                 ->toArray();

            return WorkOrderUserRoleModel::query()
                                         ->whereIn('userId', $userIds)
                                         ->pluck('feishuId')
                                         ->unique()
                                         ->values()
                                         ->toArray();
        }

        return collect(RmsUserRemote::getRmsUserByIds($userIds))->pluck('feishuUserId')->filter()->values()->toArray();
    }

    /**
     * @param array $userIds
     * @return array
     */
    public function getFsIdsByApplyManager(array $userIds): array
    {
        return WorkOrderUserRoleModel::query()
                                     ->whereIn('userId', $userIds)
                                     ->pluck('feishuId')
                                     ->unique()
                                     ->values()
                                     ->toArray();
    }

    public function getTemplateFile(string $filePath)
    {
        $template = file_get_contents(resource_path($filePath));
        $result   = array();
        preg_match_all("/\{\{(.*)\}\}/U", $template, $result);


        $params        = [];
        $paramsBracket = [];
        foreach ($result[1] as $value) {
            $params[$value]                      = $this->$value;
            $paramsBracket['{{' . $value . '}}'] = $this->$value;
        }
        $paramsKeys   = array_keys($paramsBracket);
        $paramsValues = array_values($paramsBracket);

        $template = str_replace($paramsKeys, $paramsValues, $template);

        return $template;
    }

    public function __get($paramName)
    {
        if (method_exists($this, 'get' . $paramName)) {
            return call_user_func([$this, 'get' . $paramName]);
        } else {
            dd('方法:' . 'get' . $paramName . '不存在');
        }
    }

    protected object $shopInfo;

    public function getShopInfo(): object
    {
        if (empty($this->shopInfo)) {
            $this->shopInfo = (object)current((new RmsShopApi())->getShopByIds([$this->workOrderApplyMainModel->shopId])["data"]["shopList"]);
        }

        return $this->shopInfo;
    }

    public function getShopCode()
    {
        return $this->getShopInfo()->shopCode;
    }

    public function getShopName()
    {
        return $this->getShopInfo()->name;
    }

    public function getShopBranch()
    {
        return $this->getShopInfo()->branch ?: '暂无分公司';
    }

    public function getShopProvinceText()
    {
        return explode('-', $this->getShopInfo()->addressPrefix)[0] ?? '-';
    }

    public function getShopFullProvinceCityDistrict()
    {
        return $this->getShopInfo()->addressPrefix;
    }

    public function getShopProvinceCode()
    {
        return $this->getShopInfo()->province ?? 0;
    }

    protected object $signOrder;

    public function getSignOrder(): object
    {
        if (empty($this->signOrder)) {
            $this->signOrder = $this->workOrderApplyMainModel->with([
                'openShopMainProcessRel' => function ($query) {
                    $query
                        ->with('signOrderRel')
                        ->with('userBaseInfoRel')
                        ->with('userIdentityCardRel');
                }
            ])->first();
        }

        return $this->signOrder;
    }

    public function getWorkShopUserName()
    {
        return CommonService::getUserInfoHide($this->getSignOrder()->openShopMainProcessRel->userIdentityCardRel->name ?? '', 'name');
    }

    public function getWorkShopUserMobile()
    {
        return CommonService::getUserInfoHide($this->getSignOrder()->openShopMainProcessRel->userBaseInfoRel->mobile ?? '', 'mobile');
    }

    public function getWorkOrderNo()
    {
        return $this->workOrderApplyMainModel->workOrderNo;
    }

    public function getWorkChildName(): string
    {
        return $this->workOrderApplyMainModel->getProblemChildIdTextAttribute();
    }

    public function getWorkPidName(): string
    {
        return $this->workOrderApplyMainModel->getProblemPidTextAttribute();
    }

    public function getWorkCreatedAt()
    {
        return date('m-d H:i', $this->workOrderApplyMainModel->createdAt->timestamp);
    }

    public function getWorkUpdatedAt()
    {
        return date('m-d H:i', $this->workOrderApplyMainModel->updatedAt->timestamp);
    }

    public function getNowTime()
    {
        return date('m-d H:i', time());
    }

    public object $createdUserInfo;

    public function getCreatedUserInfo()
    {
        if (empty($this->createUserInfo)) {
            $this->createUserInfo = (object)current((RmsUserRemote::getRmsUserByIds([$this->workOrderApplyMainModel->createdByUid])));
        }

        return $this->createUserInfo;
    }

    public function getCreatedUserName()
    {
        return CommonService::getUserInfoHide($this->getCreatedUserInfo()->username ?? '', 'name');
    }

    public function getCreatedUserMobile()
    {
        return CommonService::getUserInfoHide($this->getCreatedUserInfo()->mobile ?? '', 'mobile');
    }

    public function getJumpUrl()
    {
        return $this->getUrl();
    }
}
